from django.shortcuts import render
from rest_framework_jwt.views import ObtainJSONWebToken
from .serializers import CurtomJSONWebTokenSerializer


# Create your views here.
class ObtainAPIView(ObtainJSONWebToken):
    serializer_class = CurtomJSONWebTokenSerializer


from rest_framework.views import APIView
from ronglian_sms_sdk import SmsSDK
from django.conf import settings
import random, json
from luffyapi.settings import constants
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework import status


class SendSMSAPIView(APIView):
    def get(self, request, mobile):
        """获取短信验证码"""
        # 判断是否处于发送短信冷却时间内
        redis = get_redis_connection("sms_code")
        interval_time = redis.ttl("interval_%s" % mobile)
        if interval_time >= 0:
            return Response({"message": "短信已发送,请%s秒后再点击发送" % interval_time}, status=status.HTTP_403_FORBIDDEN)

        sdk = SmsSDK(
            settings.SMS.get("accId"),
            settings.SMS.get("accToken"),
            settings.SMS.get("appId"),
        )
        code = "%06d" % random.randint(0, 999999)
        try:
            resp = sdk.sendMessage(settings.SMS.get("TempId"), mobile, (code, constants.SMS_EXPIRE_TIME // 60))
            resp_data = json.loads(resp)
            if resp_data.get("statusCode") != "000000":
                raise Exception
        except:
            return Response({"message": "短信发送失败,请联系客服工作人员."}, status=status.HTTP_400_BAD_REQUEST)

        # 记录短信验证码到redis中
        pipe = redis.pipeline(0)  # 创建一个管道对象
        pipe.multi()  # 开启事务
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, code)
        pipe.setex("interval_%s" % mobile, 60, "_")
        pipe.execute()  # 执行事务,在pipe内缓存的所有命令会一并提交,要么一起成功,要么一起失败!

        return Response({"message": "短信已发送,请留意您的短信"})


from rest_framework.generics import CreateAPIView
from .models import User
from .serializers import UserModelSerializer


class UserAPIView(CreateAPIView):
    """用户管理"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer
